package cn.hd01.service.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;

import cn.hd01.repository.CustomerFeedBackRepository;
import cn.hd01.repository.StaffFeedBackRepository;
import cn.hd01.repository.TelReserveRepository;
import cn.hd01.repository.entity.CustomerFeedBack;
import cn.hd01.repository.entity.StaffFeedback;
import cn.hd01.repository.entity.TelReservation;
import cn.hd01.service.TelReserveService;

@Service
public class TelReserveServiceImpl extends BaseServiceImpl<TelReservation, Integer> implements TelReserveService {

	private TelReserveRepository repository;

	@Autowired
	private CustomerFeedBackRepository cusomerFeedBackRepository;

	@Autowired
	private StaffFeedBackRepository staffFeedBackRepository;

	@Autowired
	public TelReserveServiceImpl(TelReserveRepository repository) {
		super(repository);
		this.repository = repository;
	}

	@Override
	public List<TelReservation> findByStaffId(Integer staffId) {
		return repository.findByStaffId(staffId);
	}

	@Override
	public Page<TelReservation> findAll(final Integer customerId, Pageable pageable) {
		return repository.findAll(Specifications.where(new Specification<TelReservation>() {
			@Override
			public Predicate toPredicate(Root<TelReservation> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
				return cb.equal(r.get("customerId").as(Integer.class), customerId);
			}
		}), pageable);
	}

	@Override
	@Transactional
	public void customerFeedBack(CustomerFeedBack cusomerFeedBack) {
		repository.customerFeedBack(cusomerFeedBack.getReservationId());
		cusomerFeedBackRepository.save(cusomerFeedBack);
	}

	@Override
	public CustomerFeedBack customerFeedBack(Integer id) {
		return cusomerFeedBackRepository.findByReservationId(id);
	}

	@Override
	public void updateState(Integer id) {
		repository.updateState(id);
	}

	@Transactional
	@Override
	public void staffFeedback(StaffFeedback staffFeedback) {
		repository.staffFeedback(staffFeedback.getReservationId());
		staffFeedBackRepository.save(staffFeedback);
	}

	@Override
	public StaffFeedback staffFeedback(Integer id) {
		return staffFeedBackRepository.findByReservationId(id);
	}

}
